import React, { useState, useEffect } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Search, Filter, Star, Grid, List } from 'lucide-react';
import { productApi, categoryApi } from '@/db/api';
import type { Product, Category, ProductFilters } from '@/types/types';
import { toast } from 'sonner';

const Products: React.FC = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [searchParams, setSearchParams] = useSearchParams();
  
  const [filters, setFilters] = useState<ProductFilters>({
    search: searchParams.get('search') || '',
    category_id: '',
    min_price: undefined,
    max_price: undefined,
    is_featured: searchParams.get('featured') === 'true' ? true : undefined
  });

  useEffect(() => {
    loadCategories();
  }, []);

  useEffect(() => {
    loadProducts();
  }, [filters]);

  useEffect(() => {
    // 从URL参数初始化筛选条件
    const categoryName = searchParams.get('category');
    if (categoryName && categories.length > 0) {
      const category = categories.find(c => c.name === categoryName);
      if (category) {
        setFilters(prev => ({ ...prev, category_id: category.id }));
      }
    }
  }, [searchParams, categories]);

  const loadCategories = async () => {
    try {
      const data = await categoryApi.getCategories();
      setCategories(data);
    } catch (error) {
      console.error('加载分类失败:', error);
      toast.error('加载分类失败');
    }
  };

  const loadProducts = async () => {
    try {
      setLoading(true);
      const data = await productApi.getProducts(filters);
      setProducts(data);
    } catch (error) {
      console.error('加载商品失败:', error);
      toast.error('加载商品失败');
    } finally {
      setLoading(false);
    }
  };

  const handleFilterChange = (key: keyof ProductFilters, value: any) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  const clearFilters = () => {
    setFilters({
      search: '',
      category_id: '',
      min_price: undefined,
      max_price: undefined,
      is_featured: undefined
    });
    setSearchParams({});
  };

  const ProductCard = ({ product }: { product: Product }) => (
    <Link to={`/products/${product.id}`} className="group">
      <Card className="overflow-hidden hover:shadow-lg transition-shadow duration-300">
        <div className="aspect-square overflow-hidden">
          <img
            src={product.images?.[0] || 'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=400'}
            alt={product.name}
            className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
          />
        </div>
        <CardContent className="p-4">
          <div className="flex items-center justify-between mb-2">
            {product.is_featured && (
              <Badge variant="secondary" className="bg-pink-100 text-pink-800">
                推荐
              </Badge>
            )}
            <div className="flex items-center">
              <Star className="h-4 w-4 text-yellow-400 fill-current" />
              <span className="text-sm text-gray-600 ml-1">4.8</span>
            </div>
          </div>
          <h3 className="font-semibold text-gray-900 mb-2 group-hover:text-pink-600 transition-colors line-clamp-2">
            {product.name}
          </h3>
          <p className="text-sm text-gray-600 mb-3 line-clamp-2">
            {product.description}
          </p>
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <span className="text-lg font-bold text-pink-600">
                ¥{product.price}
              </span>
              {product.original_price && (
                <span className="text-sm text-gray-500 line-through">
                  ¥{product.original_price}
                </span>
              )}
            </div>
            <span className="text-sm text-gray-500">
              库存 {product.stock}
            </span>
          </div>
        </CardContent>
      </Card>
    </Link>
  );

  const ProductListItem = ({ product }: { product: Product }) => (
    <Link to={`/products/${product.id}`} className="group">
      <Card className="overflow-hidden hover:shadow-lg transition-shadow duration-300">
        <div className="flex">
          <div className="w-48 h-48 overflow-hidden flex-shrink-0">
            <img
              src={product.images?.[0] || 'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=400'}
              alt={product.name}
              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
            />
          </div>
          <CardContent className="flex-1 p-6">
            <div className="flex items-start justify-between mb-4">
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-2">
                  <h3 className="text-xl font-semibold text-gray-900 group-hover:text-pink-600 transition-colors">
                    {product.name}
                  </h3>
                  {product.is_featured && (
                    <Badge variant="secondary" className="bg-pink-100 text-pink-800">
                      推荐
                    </Badge>
                  )}
                </div>
                <p className="text-gray-600 mb-4 line-clamp-3">
                  {product.description}
                </p>
                <div className="flex items-center gap-4 text-sm text-gray-500">
                  <span>分类: {product.category?.name}</span>
                  <span>库存: {product.stock}</span>
                  <div className="flex items-center">
                    <Star className="h-4 w-4 text-yellow-400 fill-current mr-1" />
                    <span>4.8 (128评价)</span>
                  </div>
                </div>
              </div>
              <div className="text-right">
                <div className="flex items-center space-x-2 mb-2">
                  <span className="text-2xl font-bold text-pink-600">
                    ¥{product.price}
                  </span>
                  {product.original_price && (
                    <span className="text-lg text-gray-500 line-through">
                      ¥{product.original_price}
                    </span>
                  )}
                </div>
                <Button size="sm" className="bg-pink-600 hover:bg-pink-700">
                  查看详情
                </Button>
              </div>
            </div>
          </CardContent>
        </div>
      </Card>
    </Link>
  );

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-4">商品浏览</h1>
          <p className="text-gray-600">发现你喜欢的时尚单品</p>
        </div>

        {/* Filters */}
        <div className="bg-white rounded-lg shadow-sm p-6 mb-8">
          <div className="flex flex-col lg:flex-row gap-4">
            {/* Search */}
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-5 w-5" />
                <Input
                  placeholder="搜索商品..."
                  value={filters.search}
                  onChange={(e) => handleFilterChange('search', e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>

            {/* Category Filter */}
            <Select
              value={filters.category_id}
              onValueChange={(value) => handleFilterChange('category_id', value)}
            >
              <SelectTrigger className="w-full lg:w-48">
                <SelectValue placeholder="选择分类" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部分类</SelectItem>
                {categories.map((category) => (
                  <SelectItem key={category.id} value={category.id}>
                    {category.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            {/* Price Range */}
            <div className="flex gap-2">
              <Input
                type="number"
                placeholder="最低价格"
                value={filters.min_price || ''}
                onChange={(e) => handleFilterChange('min_price', e.target.value ? Number(e.target.value) : undefined)}
                className="w-32"
              />
              <Input
                type="number"
                placeholder="最高价格"
                value={filters.max_price || ''}
                onChange={(e) => handleFilterChange('max_price', e.target.value ? Number(e.target.value) : undefined)}
                className="w-32"
              />
            </div>

            {/* Featured Filter */}
            <Select
              value={filters.is_featured === true ? 'true' : filters.is_featured === false ? 'false' : ''}
              onValueChange={(value) => handleFilterChange('is_featured', value === 'true' ? true : value === 'false' ? false : undefined)}
            >
              <SelectTrigger className="w-full lg:w-32">
                <SelectValue placeholder="推荐" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部</SelectItem>
                <SelectItem value="true">推荐</SelectItem>
                <SelectItem value="false">普通</SelectItem>
              </SelectContent>
            </Select>

            <Button variant="outline" onClick={clearFilters}>
              <Filter className="h-4 w-4 mr-2" />
              清除
            </Button>
          </div>
        </div>

        {/* View Mode & Results */}
        <div className="flex items-center justify-between mb-6">
          <div className="text-gray-600">
            找到 {products.length} 件商品
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant={viewMode === 'grid' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setViewMode('grid')}
            >
              <Grid className="h-4 w-4" />
            </Button>
            <Button
              variant={viewMode === 'list' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setViewMode('list')}
            >
              <List className="h-4 w-4" />
            </Button>
          </div>
        </div>

        {/* Products */}
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-pink-600"></div>
          </div>
        ) : products.length === 0 ? (
          <div className="text-center py-12">
            <div className="text-gray-400 text-6xl mb-4">🛍️</div>
            <h3 className="text-lg font-semibold text-gray-900 mb-2">没有找到商品</h3>
            <p className="text-gray-600 mb-4">尝试调整筛选条件或搜索其他关键词</p>
            <Button onClick={clearFilters}>清除筛选条件</Button>
          </div>
        ) : (
          <div className={
            viewMode === 'grid'
              ? 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6'
              : 'space-y-6'
          }>
            {products.map((product) =>
              viewMode === 'grid' ? (
                <ProductCard key={product.id} product={product} />
              ) : (
                <ProductListItem key={product.id} product={product} />
              )
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default Products;